package com.tina.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Tina
 * @version 0.0.1
 * @date 2020/7/2 10:10
 * <p>
 * 手机号码短信发送认证码
 **/
public class ShortMessageUtil {
    //对应accessKeyId
    private static final String accessKeyId = "XXX";
    //对应accessKeySercret
    private static final String accessKeySercret = "XXX";
    //对应签名名称
    private static final String signname = "XXX";
    //对应模板代码
    private static final String templateCode = "XXX";
    //对应发送的验证码
    private static int moblie_code = (int) ((Math.random() * 9 + 1) * 100000);

    /**
     * 短信发送
     * @return
     */
    public static Integer SendMsg(String telphone) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySercret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        //aliyun对应发送短信的服务器地址
        request.setDomain("dysmsapi.aliyuncs.com");
        //对应版本号
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", telphone);
        request.putQueryParameter("SignName", signname);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", "{\"code\":" + moblie_code + "}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            // 返回信息
            // 返回验证码，可将验证码和手机号存入rides中，并设置多长时间过期
            System.out.println(response.getData());
            System.out.println(moblie_code);
            return moblie_code;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 验证手机号
     * @return
     * 有效返回true,否则返回false
     */
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4])|(18[0-9])|(17[0-9])|(147))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }


}
